package com.lds.config.center.client.listener.runner;

import com.lds.config.center.client.listener.ItemChangeEventListener;
import com.lds.config.center.client.service.ClientService;
import com.lds.config.center.client.service.ClientServiceImpl;
import com.lds.management.center.common.util.SpringUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.Map;
import java.util.ServiceLoader;

public class AutoAddItemChangeEventListenerRunner implements ApplicationRunner {
    private final ClientService clientService = ClientServiceImpl.getInstance();

    /**
     * 自动添加监听器
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 1. spi机制
        addListenerBySPI();

        // 2. 接口
        addListenerByInterface();

        // 3. 注解
        addListenerByAnnotation();
    }

    private void addListenerBySPI() {
        ServiceLoader<ItemChangeEventListener> serviceLoader = ServiceLoader.load(ItemChangeEventListener.class);
        for (ItemChangeEventListener itemChangeEventListener : serviceLoader) {
            clientService.addListener(itemChangeEventListener);
        }
    }

    private void addListenerByInterface() {
        Map<String, ItemChangeEventListener> listenerMap = SpringUtil.getBeansOfType(ItemChangeEventListener.class);
        if (MapUtils.isNotEmpty(listenerMap)) {
            listenerMap.values().forEach(clientService::addListener);
        }
    }

    /**
     * @see com.lds.config.center.client.listener.Annotation.ItemChangeEventListenerBeanPostProcessor
     */
    private void addListenerByAnnotation() {
    }
}
